package Socket;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @author 徐梦轲
 * @create 2022-06-25 13:45
 */
public class Client {
    DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public Client(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入要翻译的单词:");
            String request = sc.nextLine();
            if (request.equals("exit")) return;
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //读取响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //解析请求
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            //显示
            String log= String.format("[ %s : %s]",request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client("127.0.0.1",9090);
        client.start();
    }
}
